<template>
  <div class="app-container">
  <!-- 侧边栏 -->
<aside class="sidebar" v-show="sidebarVisible">
  <div class="sidebar-header">
    <h1>聊天会话</h1>

    <div class="sidebar-actions">
      <el-button type="primary" @click="createNewChat" class="new-chat-btn" title="新建聊天">
        <el-icon><Plus /></el-icon>
      </el-button>

      <el-button circle size="small" @click="sidebarVisible = false" title="关闭侧边栏">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
    </div>
  </div>

  <div class="chat-sessions">
    <div
      v-for="session in chatSessions"
      :key="session.id"
      class="chat-session"
      :class="{ active: session.id === currentSessionId }"
      @click="switchToSession(session.id)"
    >
      <span class="session-title">{{ session.title }}</span>

      <el-button
        v-if="chatSessions.length > 1"
        type="danger"
        circle
        size="small"
        class="delete-session"
        @click.stop="deleteSession(session.id)"
        title="删除会话"
      >
        <el-icon><Delete /></el-icon>
      </el-button>
    </div>
  </div>
</aside>


    <!-- 侧边栏切换按钮 -->
<div
  v-if="!sidebarVisible"
  class="sidebar-toggle"
  @click="toggleSidebar"
>
  <el-icon><ArrowRight /></el-icon>
</div>


    <!-- 主内容区 -->
    <div class="main-content">
      <div class="container">
        <header>
          <h1>青柠 Chat</h1>
        </header>

        <el-alert
          :type="connectionStatus.type"
          :title="connectionStatus.message"
          show-icon
          :closable="false"
          class="connection-status"
        />

        <!-- 配置对话框 -->
        <el-dialog v-model="settingsVisible" title="配置" width="500px">
          <el-form :model="configForm" label-width="120px">
            <el-form-item label="API 密钥">
              <el-input v-model="configForm.apiKey" type="password" placeholder="请输入 API 密钥" />
            </el-form-item>
            <el-form-item label="服务器地址">
              <el-input v-model="configForm.wsUrl" placeholder="请输入 WebSocket 服务器地址" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="settingsVisible = false">取消</el-button>
              <el-button type="primary" @click="saveSettings">保存</el-button>
            </span>
          </template>
        </el-dialog>

        <div id="chatContainer">
          <div id="chatHistory" ref="chatHistory">
            <div v-if="!hasMessages" class="empty-state">
              <el-icon size="64"><ChatLineRound /></el-icon>
              <p>开始与AI助手对话吧</p>
              <p style="font-size: 14px; margin-top: 8px;">发送消息将自动连接到服务器</p>
            </div>

            <div
              v-for="(message, index) in currentSessionMessages"
              :key="index"
              class="message"
              :class="getMessageClassString(message.role)"
            >
              <strong>{{ getMessagePrefix(message.role) }}</strong>
              <div class="message-content" v-html="renderMarkdown(message.content)"></div>
            </div>

            <div v-if="isStreaming" class="message streaming-message">
              <strong>AI:</strong>
              <div class="message-content" v-html="renderMarkdown(currentAiMessage)"></div>
              <el-icon class="streaming-spinner"><Loading /></el-icon>
            </div>
          </div>

          <div id="inputContainer">
            <el-input
              v-model="messageInput"
              type="textarea"
              placeholder="向 AI 提问..."
              class="message-input"
              :autosize="{ minRows: 1, maxRows: 6 }"
              @keydown.enter.exact.prevent="sendMessage"
              @keydown.enter.shift.exact.prevent="addNewLine"
            />
            <el-button
              type="primary"
              @click="sendMessage"
              :disabled="!messageInput.trim()"
              class="send-button"
            >
              发送
            </el-button>

            <!-- 连接状态按钮 - 仅在未连接时显示 -->
            <el-button
              v-if="!isConnected"
              type="danger"
              @click="toggleConnection"
              class="connection-button"
              title="连接服务器"
            >
              连接
            </el-button>

            <!-- 设置图标按钮 -->
            <div
              @click="openSettings"
              class="settings-icon-wrapper"
              title="设置"
            >
              <el-icon class="settings-icon"><Setting /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
/**
 * 完整组件（Vue 3 + Element Plus）
 * 依赖: marked highlight.js dompurify
 *
 * npm install marked highlight.js dompurify
 */

import { ref, onMounted, nextTick, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, ArrowLeft, ArrowRight, ChatLineRound, Loading, Setting } from '@element-plus/icons-vue'

import { marked } from 'marked'
import hljs from 'highlight.js'
import DOMPurify from 'dompurify'

// load highlight.js 默认样式（你也可以改成别的主题）
// 若你的构建工具能处理 css import，则可以在这里直接 import
import 'highlight.js/styles/github.css'



// ---------- 响应式状态 ----------
const sidebarVisible = ref(false)
const chatSessions = ref([])
const currentSessionId = ref(null)
const socket = ref(null)
const messageInput = ref('')
const isStreaming = ref(false)
const currentAiMessage = ref('')
const settingsVisible = ref(false)
const isConnected = ref(false) // 添加一个明确的连接状态跟踪

// 配置表单
const configForm = ref({
  apiKey: '',
  wsUrl: 'ws://127.0.0.1:8000'
})

const connectionStatus = ref({
  type: 'error',
  message: '未连接到服务器'
})

// ---------- 计算属性 ----------
const currentSessionMessages = computed(() => {
  const session = chatSessions.value.find(s => s.id === currentSessionId.value)
  return session ? session.messages : []
})

const hasMessages = computed(() => currentSessionMessages.value.length > 0 || isStreaming.value)
// 修改 isConnected 计算属性以使用明确的状态跟踪
// const isConnected = computed(() => socket.value && socket.value.readyState === WebSocket.OPEN)

// ---------- 设置相关 ----------
function openSettings() {
  settingsVisible.value = true
}

function saveSettings() {
  try {
    // 保存配置到 localStorage
    localStorage.setItem('mcpConfig', JSON.stringify({ 
      apiKey: configForm.value.apiKey,
      wsUrl: configForm.value.wsUrl 
    }))
    ElMessage.success('配置已保存')
    settingsVisible.value = false
    
    // 如果已经连接，重新连接以使用新配置
    if (isConnected.value) {
      socket.value?.close()
      connect()
    }
  } catch (e) {
    console.error('保存配置失败', e)
    ElMessage.error('保存配置失败')
  }
}

function loadConfigFromStorage() {
  try {
    const raw = localStorage.getItem('mcpConfig')
    if (raw) {
      const parsed = JSON.parse(raw)
      if (typeof parsed === 'object' && parsed !== null) {
        configForm.value = {
          apiKey: parsed.apiKey || '',
          wsUrl: parsed.wsUrl || 'ws://127.0.0.1:8000'
        }
      }
    }
  } catch (e) {
    console.error('加载配置失败', e)
  }
}

// ---------- WebSocket 相关 ----------
function updateConnectionStatus(connected, message) {
  isConnected.value = connected; // 更新明确的连接状态
  connectionStatus.value = {
    type: connected ? 'success' : 'error',
    message: message || (connected ? '已连接到服务器' : '未连接到服务器')
  }
}

function toggleConnection() {
  if (isConnected.value) {
    socket.value?.close()
  } else {
    connect()
  }
}

function connect() {
  if (!configForm.value.apiKey.trim()) {
    ElMessage.warning('请先在设置中配置 API 密钥')
    settingsVisible.value = true
    return
  }

  connectionStatus.value = { type: 'info', message: '正在连接...' }

  const wsUrl = `${configForm.value.wsUrl}/ws?api_key=${encodeURIComponent(configForm.value.apiKey)}`
  try {
    socket.value = new WebSocket(wsUrl)
  } catch (e) {
    connectionStatus.value = { type: 'error', message: 'WebSocket 创建失败' }
    console.error(e)
    return
  }

  socket.value.onopen = () => {
    updateConnectionStatus(true, '已连接到服务器')
    addMessageToHistory('system', '已连接到AI助手服务器')
  }

  socket.value.onmessage = (event) => {
    let data = null
    try {
      data = JSON.parse(event.data)
    } catch (e) {
      console.warn('非JSON消息:', event.data)
      return
    }
    handleServerMessage(data)
  }

  socket.value.onclose = (event) => {
    updateConnectionStatus(false, '连接已断开')
    isStreaming.value = false
    currentAiMessage.value = ''
  }

  socket.value.onerror = (err) => {
    updateConnectionStatus(false, '连接错误')
    console.error('WebSocket 错误', err)
  }
}

// 等待 socket 打开（最多等待 timeOutMs 毫秒）
function waitForSocketOpen(timeOutMs = 5000) {
  return new Promise((resolve, reject) => {
    const start = Date.now()
    const timer = setInterval(() => {
      if (socket.value && socket.value.readyState === WebSocket.OPEN) {
        updateConnectionStatus(true, '已连接到服务器') // 确保状态同步
        clearInterval(timer)
        resolve(true)
      } else if (Date.now() - start > timeOutMs) {
        clearInterval(timer)
        reject(new Error('连接超时'))
      }
    }, 100)
  })
}

// ---------- 会话管理 ----------
function createNewChat() {
  const sessionId = Date.now().toString()
  const newSession = { id: sessionId, title: '新聊天', messages: [] }
  chatSessions.value.unshift(newSession)
  currentSessionId.value = sessionId
  sidebarVisible.value = true // ✅ 新建会话后自动打开侧边栏
  saveSessionsToStorage()
  nextTick(() => scrollToBottom())
}


function switchToSession(id) {
  if (!id) return
  const exists = chatSessions.value.find(s => s.id === id)
  if (!exists) return
  currentSessionId.value = id
  saveSessionsToStorage()
  nextTick(() => scrollToBottom())
}

function deleteSession(id) {
  if (!id) return
  if (chatSessions.value.length <= 1) {
    ElMessage.warning('至少保留一个会话')
    return
  }
  const idx = chatSessions.value.findIndex(s => s.id === id)
  if (idx === -1) return
  chatSessions.value.splice(idx, 1)
  // 调整当前会话
  if (currentSessionId.value === id) {
    currentSessionId.value = chatSessions.value[0].id
  }
  saveSessionsToStorage()
}

// ---------- 消息处理 ----------
function ensureSessionExists() {
  if (!currentSessionId.value) {
    const id = Date.now().toString()
    chatSessions.value.unshift({ id, title: '新聊天', messages: [] })
    currentSessionId.value = id
  }
}

function addMessageToHistory(role, content) {
  ensureSessionExists()
  const session = chatSessions.value.find(s => s.id === currentSessionId.value)
  if (!session) return
  session.messages.push({ role, content: content ?? '' })
  saveSessionsToStorage()
  scrollToBottom()
  // 确保代码高亮
  highlightCodeBlocks()
}

function handleServerMessage(data) {
  // 根据服务器协议处理
  if (!data || typeof data !== 'object') return
  const t = data.type
  switch (t) {
    case 'connection_status':
      if (data.message) addMessageToHistory('system', data.message)
      break
    case 'processing_start':
      if (data.message) addMessageToHistory('system', data.message)
      break
    case 'response':
      // 完整响应
      addMessageToHistory('ai', data.content ?? '')
      break
    case 'streaming':
      // 处理流式消息片段
      if (data.content) {
        isStreaming.value = true
        currentAiMessage.value += data.content
        scrollToBottom()
        // 流式消息也需要高亮处理
        highlightCodeBlocks()
      }
      break
    case 'streaming_complete':
      if (isStreaming.value) {
        // 把拼接的内容作为一条 ai 消息
        addMessageToHistory('ai', currentAiMessage.value)
        isStreaming.value = false
        currentAiMessage.value = ''
      } else if (data.content) {
        addMessageToHistory('ai', data.content)
      }
      break
    case 'error':
      addMessageToHistory('error', data.content ?? '未知错误')
      isStreaming.value = false
      currentAiMessage.value = ''
      break
    default:
      // 对于未识别的类型，如果包含content则作为AI消息处理
      if (data.content) {
        addMessageToHistory('ai', data.content)
      } else {
        console.warn('未知服务器消息类型:', data)
      }
  }
}

// ---------- 发送消息 ----------
async function sendMessage() {
  const msg = messageInput.value.trim()
  if (!msg) return

  // 确保有会话
  ensureSessionExists()

  // 确保有 API Key
  if (!configForm.value.apiKey.trim()) {
    try {
      ElMessage.warning('请先在设置中配置 API 密钥')
      settingsVisible.value = true
      return
    } catch (e) {
      return // 用户取消输入
    }
  }

  // 建立连接（如果没连）
  if (!isConnected.value) {
    connect()
    try {
      await waitForSocketOpen(5000)
    } catch (e) {
      ElMessage.error('连接超时，发送失败')
      return
    }
  }

  // 发送消息
  const session = chatSessions.value.find(s => s.id === currentSessionId.value)
  // 添加用户消息到本地历史
  addMessageToHistory('user', msg)

  // 如果是会话第一条消息，用来更新标题
  if (session && session.title === '新聊天' && session.messages.length > 0) {
    // 取第一条非系统消息作为标题
    const firstUser = session.messages.find(m => m.role === 'user' || m.role === 'ai')
    if (firstUser) {
      session.title = (firstUser.content || '').substring(0, 30) || '会话'
      saveSessionsToStorage()
    }
  }

  // 发送到服务器
  try {
    socket.value?.send(JSON.stringify({
      type: 'query',
      query: msg,
      session_id: currentSessionId.value
    }))
  } catch (e) {
    ElMessage.error('发送失败：' + e.message)
    console.error(e)
  }

  // 清空输入框
  messageInput.value = ''
}

// ---------- Markdown 渲染（带高亮 & 安全过滤） ----------
function renderMarkdown(text) {
  try {
    // 处理换行符
    const processedText = String(text ?? '').replace(/\n/g, '<br>')
    
    const html = marked.parse(processedText, {
      gfm: true,
      breaks: true,
      highlight: (code, lang) => {
        // ✅ 如果指定了语言且 highlight.js 支持
        if (lang && hljs.getLanguage(lang)) {
          try {
            return hljs.highlight(code, { language: lang }).value
          } catch (e) {
            console.warn('语言高亮失败:', e)
            return hljs.highlightAuto(code).value
          }
        }
        // ✅ 否则自动检测语言
        try {
          return hljs.highlightAuto(code).value
        } catch (e) {
          console.warn('自动高亮失败:', e)
          return code
        }
      }
    })

    // ✅ DOMPurify 允许保留必要的属性
    const clean = DOMPurify.sanitize(html, {
      ALLOWED_TAGS: ['br', 'p', 'strong', 'em', 'code', 'pre', 'span', 'div', 'ul', 'ol', 'li', 'a', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
      ALLOWED_ATTR: ['class', 'href', 'src', 'alt', 'title', 'rel', 'target', 'id']
    })

    return clean
  } catch (e) {
    console.error('Markdown 渲染错误:', e)
    return DOMPurify.sanitize(String(text))
  }
}

// ---------- 语音播报 ----------
// 已移除语音播报相关功能

// ---------- 工具 / 存储 ----------
function scrollToBottom() {
  nextTick(() => {
    const el = document.getElementById('chatHistory')
    if (el) {
      el.scrollTop = el.scrollHeight
    }
  })
}

// 代码高亮处理函数
function highlightCodeBlocks() {
  nextTick(() => {
    // 查找所有未处理的代码块
    document.querySelectorAll('.message-content pre code').forEach((el) => {
      try {
        // 如果还没有 hljs 类，则进行高亮处理
        if (!el.classList.contains('hljs')) {
          hljs.highlightElement(el)
          el.classList.add('hljs')
        }
      } catch (e) {
        console.warn('代码高亮失败:', e)
      }
    })
  })
}

function addNewLine() {
  messageInput.value += '\n'
}

function toggleSidebar() {
  sidebarVisible.value = !sidebarVisible.value
}

function saveSessionsToStorage() {
  try {
    localStorage.setItem('mcpChatSessions', JSON.stringify(chatSessions.value))
  } catch (e) {
    console.error('保存会话失败', e)
  }
}

function loadSessionsFromStorage() {
  try {
    const raw = localStorage.getItem('mcpChatSessions')
    if (raw) {
      const parsed = JSON.parse(raw)
      if (Array.isArray(parsed)) {
        chatSessions.value = parsed
        currentSessionId.value = parsed[0]?.id ?? null
      }
    }
  } catch (e) {
    console.error('加载会话失败', e)
    chatSessions.value = []
    currentSessionId.value = null
  }
}

// ---------- UI 帮助 ----------
function getMessageClassString(role) {
  switch (role) {
    case 'user': return 'user-message'
    case 'ai': return 'ai-message'
    case 'error': return 'error-message'
    case 'system': return 'tool-message'
    default: return 'ai-message'
  }
}
function getMessagePrefix(role) {
  switch (role) {
    case 'user': return '你'
    case 'ai': return 'AI'
    case 'error': return '系统'
  
    
  }
}

// ---------- 生命周期 ----------
onMounted(() => {
  loadSessionsFromStorage()
  loadConfigFromStorage() // 加载配置
  if (chatSessions.value.length === 0) createNewChat()
  
  // 监听消息变化，确保代码高亮
  watch(
    () => currentSessionMessages.value,
    async () => {
      await nextTick()
      document.querySelectorAll('pre code').forEach((el) => {
        try {
          hljs.highlightElement(el)
        } catch (e) {
          console.warn('代码高亮失败', e)
        }
      })
    },
    { deep: true }
  )
  
  // 初始加载时也执行一次代码高亮
  nextTick(() => {
    document.querySelectorAll('pre code').forEach((el) => {
      try {
        hljs.highlightElement(el)
      } catch (e) {
        console.warn('代码高亮失败', e)
      }
    })
  })
})
sidebarVisible.value = true
</script>

<style scoped>
:root {
  --bg-color: #ffffff;
  --text-color: #333333;
  --sidebar-bg: #f8f9fa;
  --sidebar-hover: #e9ecef;
  --sidebar-active: #e1f5fe;
  --user-bg: #1a73e8;
  --user-text: #ffffff;
  --ai-bg: #4285f4;
  --ai-text: #ffffff;
  --border-color: #e5e5e5;
  --input-bg: #ffffff;
  --button-bg: #007bff;
  --shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.app-container {
  display: flex;
  height: 100vh;
  background: var(--bg-color);
}

/* ✅ 修复：侧边栏与主内容背景统一 */
.sidebar {
  width: 280px;
  background: var(--sidebar-bg);
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  height: 100vh;
  transition: transform 0.3s ease;
}

/* ✅ 修复隐藏时滑动效果不会留下白块 */
.sidebar[style*="display: none"] {
  transform: translateX(-100%);
  position: absolute;
  left: 0;
}

/* 侧边栏头部 */
.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  border-bottom: 1px solid var(--border-color);
}

/* 会话列表 */
.chat-sessions {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
}

/* 代码块和内联代码（针对 message-content）*/
.message-content :deep(pre),
.message-content :deep(pre code) {
  display: block;
  width: 100%;
  background: #f6f8fa;
  padding: 12px;
  border-radius: 8px;
  overflow-x: auto;
  border: 1px solid #e1e4e8;
  white-space: pre;
  line-height: 1.45;
  margin: 8px 0;
  font-family: 'Fira Code', 'Source Code Pro', monospace;
  font-size: 13px;
}

/* 行内代码样式（短片段）*/
.message-content :deep(code) {
  background: rgba(0,0,0,0.04);
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Fira Code', 'Source Code Pro', monospace;
  font-size: 13px;
  white-space: pre-wrap;
}

/* hljs 代码高亮样式 */
.message-content :deep(pre code.hljs) {
  background: #f6f8fa;
  padding: 12px;
  border-radius: 8px;
  overflow-x: auto;
  white-space: pre;
  font-family: 'Fira Code', 'Source Code Pro', monospace;
  font-size: 13px;
}

.chat-session {
  padding: 10px 12px;
  border-radius: 8px;
  margin-bottom: 6px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background 0.15s;
}

.chat-session:hover {
  background: var(--sidebar-hover);
}
.chat-session.active {
  background: var(--sidebar-active);
  font-weight: 600;
}

.session-title {
  flex: 1;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.delete-session {
  opacity: 0;
  transition: opacity 0.15s;
}
.chat-session:hover .delete-session {
  opacity: 1;
}

/* 侧边栏切换按钮 */
.sidebar-toggle {
  position: absolute;
  left: 0;
  top: 16px;
  background-color: var(--sidebar-bg);
  border: 1px solid var(--border-color);
  border-left: none;
  width: 36px;
  height: 36px;
  border-radius: 0 8px 8px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

/* 主内容区 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: var(--bg-color);
}

/* 容器布局 */
.container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

header h1 {
  text-align: center;
  font-size: 20px;
  margin-bottom: 12px;
  flex: 1;
}

/* 聊天主容器 */
#chatContainer {
  display: flex;
  flex-direction: column;
  flex: 1;
  gap: 12px;
  background-color: var(--bg-color);
  border-radius: 12px;
  box-shadow: var(--shadow);
  overflow: hidden;
}

/* 聊天历史区 */
#chatHistory {
  flex: 1;
  overflow-y: auto;
  padding: 18px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  scroll-behavior: smooth;
  background: var(--bg-color);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 240px;
  color: var(--text-color);
  opacity: 0.7;
}

/* 消息气泡样式 */
.message {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 18px;
  word-break: break-word;
  line-height: 1.5;
  animation: fadeIn 0.18s ease;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

/* 用户消息气泡 - 深蓝色背景，右侧对齐 */
.user-message {
  background: #edf0f0;
  color: #0e0d0d;
  align-self: flex-end;
  border-bottom-right-radius: 4px;
}

/* AI消息气泡 - 浅蓝色背景，左侧对齐 */
.ai-message {
  background: #dbeafe;
  color: #0d0d0e;
  align-self: flex-start;
  border-bottom-left-radius: 4px;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
}

/* 系统/工具消息 - 保持简洁样式，无气泡 */
.tool-message {
  background: transparent;
  color: #555;
  font-size: 13px;
  padding: 0px 0;
  max-width: 100%;
  align-self: flex-start;
  white-space: pre-wrap;
  word-break: break-word;
  border-radius: 0;
  text-align: center
}

/* 错误消息 - 保持简洁样式，无气泡 */
.error-message {
  background: transparent;
  color: #a00;
  align-self: flex-start;
  padding: 8px 0;
  border-left: none;
  text-align: left;
}

/* 流式消息 - 保持简洁样式，无气泡 */
.streaming-message {
  background: transparent;
  color: #856404;
  font-style: italic;
  align-self: flex-start;
  padding: 8px 0;
  text-align: left;
}

/* 输入框区 */
#inputContainer {
  display: flex;
  gap: 8px;
  padding: 12px;
  background: var(--bg-color);
  border-top: 1px solid var(--border-color);
}
.message-input {
  flex: 1;
}
.message-input :deep(.el-textarea__inner) {
  border-radius: 20px;
  padding: 12px 14px;
  font-size: 14px;
}

/* 按钮 */
.send-button {
  align-self: flex-end;
}

.connection-button {
  align-self: flex-end;
  padding: 8px 12px;
  font-size: 12px;
}

.settings-icon-wrapper {
  align-self: flex-end;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.settings-icon-wrapper:hover {
  background-color: #f0f0f0;
}

.settings-icon {
  font-size: 20px;
  color: #666;
}

/* 加载旋转图标 */
.streaming-spinner {
  margin-left: 8px;
  vertical-align: middle;
  display: inline-block;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(6px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式优化 */
@media (max-width: 768px) {
  .app-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
    max-height: 40vh;
    border-right: none;
    border-bottom: 1px solid var(--border-color);
  }
  
  .sidebar-toggle {
    top: 8px;
  }
  
  .chat-session {
    padding: 8px;
  }
  
  .container {
    padding: 10px;
  }
  
  header h1 {
    font-size: 18px;
    margin-bottom: 8px;
  }
  
  #chatContainer {
    gap: 8px;
  }
  
  #chatHistory {
    padding: 12px;
    gap: 10px;
  }
  
  .message {
    max-width: 90%;
    padding: 10px 14px;
    border-radius: 16px;
  }
  
  #inputContainer {
    flex-direction: column;
    gap: 8px;
    padding: 8px;
  }
  
  .message-input :deep(.el-textarea__inner) {
    border-radius: 16px;
    padding: 10px 12px;
    font-size: 14px;
  }
  
  .send-button {
    align-self: flex-end;
    width: 100%;
    height: 36px;
  }
  
  .connection-button {
    align-self: flex-end;
    width: 100%;
    height: 36px;
    padding: 6px 12px;
    font-size: 14px;
  }
  
  .settings-icon-wrapper {
    position: absolute;
    right: 12px;
    bottom: 60px;
    background-color: var(--bg-color);
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  .empty-state {
    height: 200px;
  }
  
  .empty-state el-icon {
    font-size: 48px;
  }
  
  .empty-state p {
    font-size: 14px;
  }
}

/* 小屏幕设备优化 */
@media (max-width: 480px) {
  .sidebar-header {
    padding: 8px 10px;
  }
  
  .sidebar-header h1 {
    font-size: 16px;
  }
  
  .chat-session {
    padding: 6px 10px;
    margin-bottom: 4px;
  }
  
  .session-title {
    font-size: 14px;
  }
  
  .message {
    max-width: 95%;
    padding: 8px 12px;
    border-radius: 14px;
  }
  
  .message-content {
    font-size: 14px;
  }
  
  .tool-message, .error-message, .streaming-message {
    font-size: 12px;
  }
  
  .message-input :deep(.el-textarea__inner) {
    border-radius: 14px;
    padding: 8px 10px;
    font-size: 13px;
  }
  
  .send-button, .connection-button {
    height: 32px;
    font-size: 13px;
  }
  
  .settings-icon {
    font-size: 18px;
  }
}

</style>
